package com.wn.project.service.impl;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wn.common.PageBean;
import com.wn.entity.Procedure;
import com.wn.project.mapper.ProcedureMapper;
import com.wn.project.service.ProcedureService;
import com.wn.utils.PageBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: pms
 * @ClassName ProcedureServiceImpl
 * @description:
 * @author: LRW
 * @create: 2022-10-25 14:16
 * @Version 1.0
 **/
@Service
public class ProcedureServiceImpl implements ProcedureService {

    @Autowired
    private ProcedureMapper procedureMapper;

    @Override
    public void add(Procedure procedure) {
        int size = procedureMapper.selectByProjectId(procedure.getProjectId()).size() + 1;
        if (size < 10){
            procedure.setNo("P0"+String.valueOf(size)); //设置编号
        } else {
            procedure.setNo("P"+String.valueOf(size)); //设置编号
        }
        DateTime start = DateUtil.parse(procedure.getStartTime());
        DateTime end = DateUtil.parse(procedure.getEndTime());
        String duration = DateUtil.formatBetween(DateUtil.betweenMs(start, end), BetweenFormatter.Level.DAY);
        procedure.setDuration(duration);
        procedureMapper.add(procedure);
    }

    @Override
    public void deleteById(int id) {
        procedureMapper.deleteById(id);
    }

    @Override
    public void update(Procedure procedure) {
        if (StrUtil.isNotBlank(procedure.getStartTime()) ||StrUtil.isNotBlank(procedure.getEndTime())){
            DateTime start = DateUtil.parse(procedure.getStartTime());
            DateTime end = DateUtil.parse(procedure.getEndTime());
            String duration = DateUtil.formatBetween(DateUtil.betweenMs(start, end), BetweenFormatter.Level.DAY);
            procedure.setDuration(duration);
        }
        procedureMapper.update(procedure);
    }

    @Override
    public PageBean<Procedure> getByProjectId(int id, int currPage) {
        int pageSize = 15;
        Page<Procedure> page = PageHelper.startPage(currPage, pageSize);
        List<Procedure> list = procedureMapper.selectByProjectId(id);
        return PageBeanUtil.getPageBean(list, page, currPage, pageSize);
    }

    @Override
    public Procedure getById(int id) {
        return procedureMapper.selectById(id);
    }
}
